<template>
  <el-dialog
    class="addedit-invoicing-dialog"
    width="1300px"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    v-dialogDrag="true"
    append-to-body
    @open="handleDialogOpen"
    @closed="handleDialogClosed"
  >
    <template slot="title">
      <span class="el-dialog__title" v-if="operType == 'add'">新增开票申请</span>
      <span class="el-dialog__title" v-if="operType == 'edit'">修改开票申请</span>
      <span class="el-dialog__title" v-if="operType == 'update'">补录开票信息</span>
      <span class="el-dialog__title" v-if="operType == 'detail'">查看开票申请</span>
    </template>

    <el-form
      ref="addEditInvoicingForm"
      :model="formData"
      :rules="formRules"
      size="small"
      label-width="100px"
      :disabled="operType == 'detail'"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="申请人:" prop="applyUser">
            <el-select
              style="width: 100%;"
              v-model="formData.applyUser"
              clearable
              filterable
              :disabled="operType == 'update'"
            >
              <el-option
                v-for="(item, index) in userList"
                :key="index"
                :label="item.nickName"
                :value="item.userId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门:" prop="applyDept">
            <el-select
              style="width: 100%;"
              v-model="formData.applyDept"
              clearable
              filterable
              :disabled="operType == 'update'"
            >
              <el-option
                v-for="(item, index) in saleDeptList"
                :key="index"
                :label="item.deptName"
                :value="item.deptId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="申请日期:" prop="applyDate">
            <el-date-picker
              style="width: 100%;"
              v-model="formData.applyDate"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="请选择"
              :disabled="operType == 'update'"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户:" prop="entrustOrganizationId">
            <OrganizationSelect
              style="width: 100%;"
              ref="clientOrganizationSelect"
              v-model="formData.entrustOrganizationId"
              @change="(value) => {
                agreementList = []
                formData.agreements = []
                getInvoiceAgreement(true)
              }"
              :disabled="operType == 'update'"
            ></OrganizationSelect>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="" prop="" label-width="25px">
            <div style="margin-bottom: 10px;">
              <label style="margin-right: 20px;">关联合同:</label>
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddContract" v-if="operType != 'update'">更多合同</el-button>
            </div>
            <el-table
              style="width: 100%"
              :data="formData.agreements"
            >
              <el-table-column label="" prop="" width="35" v-if="operType == 'update'">
                <template slot-scope="scope">
                  <el-radio v-model="contractRadioIndex" :label="scope.$index">{{ '' }}</el-radio>
                </template>
              </el-table-column>
              <el-table-column label="选择" prop="agreementId" align="center" width="200" key="agreementId" v-if="operType != 'detail'">
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.agreementId"
                    :clearable="true"
                    :filterable="true"
                    @change="(value) => {
                      const findRes = agreementList.find(item => item.agreementId == value)
                      scope.row = Object.assign(scope.row, findRes || {})
                    }"
                    :disabled="operType == 'update'"
                  >
                    <el-option
                      v-for="(item, index) in agreementList"
                      :key="index"
                      :label="item.organizationName"
                      :value="item.agreementId"
                    >
                      <span>{{ item.organizationName }}({{ item.agreementNumber }})</span>
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column type="index" label="序号" align="center" width="50" key="index">
              </el-table-column>
              <el-table-column label="日期/编号" prop="" align="center" min-width="120" key="agreementNumber">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
                  <br/>
                  <span>{{ scope.row.agreementNumber }}</span>
                </template>
              </el-table-column>
              <el-table-column label="项目" prop="itemName" align="center" min-width="120" key="itemName">
                <template slot-scope="scope">
                  <span>{{ scope.row.itemName }}</span>
                </template>
              </el-table-column>
              <el-table-column label="业务员/部门" align="center" prop="" min-width="100" key="businessUserName">
                <template slot-scope="scope">
                  <span>{{ scope.row.businessUserName }}</span>
                  <br/>
                  <span>{{ scope.row.deptName }}</span>
                </template>
              </el-table-column>
              <el-table-column label="备注/附言" align="center" prop="remark" min-width="100" key="remark">
                <template slot-scope="scope">
                  <span>{{ scope.row.remark }}</span>
                  <br/>
                  <span>{{ scope.row.postscript }}</span>
                </template>
              </el-table-column>
              <el-table-column label="合同金额" align="center" prop="actualAmount" min-width="80" key="actualAmount">
                <template slot-scope="scope">
                  <span>{{ scope.row.actualAmount }}</span>
                </template>
              </el-table-column>
              <el-table-column label="已收款" align="center" prop="paymentAmount" min-width="80" key="paymentAmount">
                <template slot-scope="scope">
                  <span>{{ scope.row.paymentAmount }}</span>
                </template>
              </el-table-column>
              <el-table-column label="已开票" align="center" prop="invoiceAmount" min-width="70" key="invoiceAmount">
                <template slot-scope="scope">
                  <span>{{ scope.row.invoiceAmount }}</span>
                </template>
              </el-table-column>
              <el-table-column label="开票中" align="center" prop="progressInvoiceAmount" min-width="70" key="progressInvoiceAmount" v-if="operType != 'detail'">
                <template slot-scope="scope">
                  <span>{{ scope.row.progressInvoiceAmount }}</span>
                </template>
              </el-table-column>
              <el-table-column label="开票金额" align="center" prop="agreementInvoiceAmount" min-width="100" key="agreementInvoiceAmount">
                <template slot-scope="scope">
                  <el-input-number
                    style="width: 100%;"
                    v-model="scope.row.agreementInvoiceAmount"
                    placeholder="请输入"
                    :min="0"
                    :precision="2"
                    :controls="false"
                    :disabled="operType == 'update'"
                    @blur="calculateActualAmount"
                  ></el-input-number>
                </template>
              </el-table-column>
              <!-- 补录和查看 不可操作 -->
              <el-table-column label="操作" align="center" prop="" width="60" key="oper" v-if="operType != 'update' && operType != 'detail'">
                <template slot-scope="scope">
                  <el-link type="danger" @click="handleRemoveContract(scope.$index)">删除</el-link>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="operType === 'update' || operType === 'detail'">
        <el-col :span="24">
          <el-form-item label="" prop="" label-width="25px">
            <div style="margin-bottom: 10px;">
              <label style="margin-right: 20px;">开票明细:</label>
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddDetail">添加</el-button>
            </div>
            <el-table
              style="width: 100%"
              :data="formData.applyDetails"
            >
              <el-table-column type="index" label="序号" align="center" width="50" key="index">
              </el-table-column>
              <el-table-column label="合同编号" align="center" prop="agreementNumber" min-width="80" key="agreementNumber" v-if="operType === 'detail'">
                <template slot-scope="scope">
                  {{ scope.row.agreementNumber }}
                </template>
              </el-table-column>
              <el-table-column label="货物名称" align="center" prop="goodsName" min-width="80" key="goodsName">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.goodsName" placeholder="请输入"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="规格型号" align="center" prop="specifications" min-width="80" key="specifications">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.specifications" placeholder="请输入"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="单位" align="center" prop="unit" min-width="70" key="unit">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.unit" placeholder="请输入"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="数量" align="center" prop="quantity" min-width="100" key="quantity">
                <template slot-scope="scope">
                  <el-input-number
                    style="width: 100%;"
                    v-model="scope.row.quantity"
                    placeholder="请输入"
                    :min="0"
                    :precision="0"
                    :controls="false"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="单价" align="center" prop="price" min-width="100" key="price">
                <template slot-scope="scope">
                  <el-input-number
                    style="width: 100%;"
                    v-model="scope.row.price"
                    placeholder="请输入"
                    :min="0"
                    :precision="2"
                    :controls="false"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="金额" align="center" prop="amount" min-width="100" key="amount">
                <template slot-scope="scope">
                  <el-input-number
                    style="width: 100%;"
                    v-model="scope.row.amount"
                    placeholder="请输入"
                    :min="0"
                    :precision="2"
                    :controls="false"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="税率" align="center" prop="detailTaxRate" min-width="100" key="detailTaxRate">
                <template slot-scope="scope">
                  <el-input-number
                    style="width: 100%;"
                    v-model="scope.row.detailTaxRate"
                    placeholder="请输入"
                    :min="0"
                    :precision="2"
                    :controls="false"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="税额" align="center" prop="taxAmount" min-width="100" key="taxAmount">
                <template slot-scope="scope">
                  <el-input-number
                    style="width: 100%;"
                    v-model="scope.row.taxAmount"
                    placeholder="请输入"
                    :min="0"
                    :precision="2"
                    :controls="false"
                  ></el-input-number>
                </template>
              </el-table-column>
              <!-- 查看 不可操作 -->
              <el-table-column label="操作" align="center" prop="" width="60" key="oper" v-if="operType != 'detail'">
                <template slot-scope="scope">
                  <el-link type="danger" @click="handleRemoveDetail(scope.$index)">删除</el-link>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="发票类型:" prop="invoiceType">
            <el-select
              style="width: 100%;"
              v-model="formData.invoiceType"
              clearable
            >
              <el-option
                v-for="(item, index) in dict.type.invoice_type"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="销方公司:" prop="sellingParty">
            <el-select
              style="width: 100%;"
              v-model="formData.sellingParty"
              clearable
              filterable
              @change="handleSellingPartyChange"
            >
              <el-option
                v-for="(item, index) in saleDeptList"
                :key="index"
                :label="item.deptName"
                :value="item.deptId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="税率:" prop="taxRate">
            <el-input-number
              style="width: 100%;"
              v-model="formData.taxRate"
              placeholder="请输入"
              :min="0"
              :precision="2"
              :controls="false"
            ></el-input-number>
            <span class="append">%</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="operType === 'update' || operType === 'detail'">
        <el-col :span="12">
          <el-form-item label="发票号码:" prop="invoiceNumber">
            <el-input style="width: 100%;" v-model="formData.invoiceNumber" placeholder="请输入" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开票日期:" prop="invoiceDate">
            <el-date-picker
              style="width: 100%;"
              v-model="formData.invoiceDate"
              placeholder="请选择"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="发票抬头:" :prop="!isAddInvoiceHeader ? 'invoiceHeaderId' : 'invoiceHeaderName'">
            <div style="display: flex;">
              <el-select
                v-if="!isAddInvoiceHeader"
                style="width: 100%;"
                v-model="formData.invoiceHeaderId"
                clearable
                filterable
                @change="(value) => {
                  const findRes = invoiceList.find(item => item.invoiceHeaderId == value)
                  formData.taxId = findRes ? findRes.taxId : ''
                  formData.openBank = findRes ? findRes.openBank : ''
                  formData.bankAccount = findRes ? findRes.bankAccount : ''
                  formData.contactNumber = findRes ? findRes.contactNumber : ''
                  formData.address = findRes ? findRes.address : ''
                  formData.invoiceHeaderName = findRes ? findRes.companyName : ''
                }"
                :disabled="operType == 'update'"
              >
                <el-option
                  v-for="(item, index) in invoiceList"
                  :key="index"
                  :label="item.companyName"
                  :value="item.invoiceHeaderId"
                ></el-option>
              </el-select>
              <el-input v-else style="width: 100%;" v-model="formData.invoiceHeaderName" placeholder="请输入抬头名称" :disabled="operType == 'update'">
                <el-button slot="append" @click="handleInvoiceHeaderName"><svg-icon icon-class="qcc" class="qcc" /></el-button>
              </el-input>
              <el-button style="margin-left: 4px;" icon="el-icon-plus" size="mini" plain type="primary" @click="handleAddInvoicHead" v-if="operType != 'update'">{{ !isAddInvoiceHeader ? '新增抬头' : '选择抬头'}}</el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="税号:" prop="taxId">
            <el-input v-model="formData.taxId" placeholder="请输入" clearable :disabled="operType == 'update'"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="开户行:" prop="openBank">
            <el-input v-model="formData.openBank" placeholder="请输入" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="银行账号:" prop="bankAccount">
            <el-input v-model="formData.bankAccount" placeholder="请输入" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="联系电话:" prop="contactNumber">
            <el-input v-model="formData.contactNumber" placeholder="请输入" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="地址:" prop="address">
            <el-input v-model="formData.address" placeholder="请输入" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item class="line-1" label="开票申请合计金额:" prop="totalAmount">
            <el-input-number
              style="width: 100%;"
              v-model="formData.totalAmount"
              placeholder="请输入"
              :min="0"
              :precision="2"
              :controls="false"
              :disabled="true"
            ></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="移交方式:" prop="transferMethod">
            <el-select
              style="width: 100%;"
              v-model="formData.transferMethod"
              clearable
            >
              <el-option
                v-for="(item, index) in dict.type.invoice_transfer_method"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="审批人:" prop="approveUser">
            <el-select
              style="width: 100%;"
              v-model="formData.approveUser"
              clearable
              filterable
              :disabled="operType == 'update'"
            >
              <el-option
                v-for="(item, index) in approverList"
                :key="index"
                :label="item.nickName"
                :value="item.userId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="备注:" prop="remark">
            <el-input
              type="textarea"
              rows="3"
              maxlength="100"
              show-word-limit
              v-model="formData.remark"
              placeholder="请输入"
              clearable
              :disabled="operType == 'update'"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="附件:" prop="attachment">
            <el-upload
              ref="attachmentUploadRef"
              :action="uploadParams.url"
              :headers="uploadParams.headers"
              :before-upload="handleBeforeUpload"
              :on-success="handleSuccessFile"
              :on-error="handleErrorFile"
              :on-remove="handleRemoveFile"
              :on-preview="handlePreviewFile"
              :file-list="attachmentFileList"
              multiple
            >
              <el-button icon="el-icon-upload" size="mini" plain type="primary">添加附件</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="dialog-footer" slot="footer">
      <template v-if="operType != 'detail'">
        <!-- 新增/修改操作 才有暂存 -->
        <el-button style="margin-right: 50px;" type="primary" @click="handleSave(false)" v-if="operType == 'add' || operType == 'edit'">暂存</el-button>
        <el-button style="margin-right: 50px;" type="primary" @click="handleSave(true)">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </template>
      <template v-if="operType == 'detail'">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button style="margin-right: 50px;" type="primary" @click="handleChangeSendStatus">发票已开并发送</el-button>
      </template>
    </div>
  </el-dialog>
</template>

<script>
import { userListingIgnorePermission } from '@/api/system/user'
import { listDeptIgnorePermission } from '@/api/system/dept'
import { invoiceListAll } from '@/api/person/invoice'
import {
  queryInvoiceAgreement,
  invoicingDetail,
  invoicingAdd,
  invoicingEdit,
  invoicingOper,
  changeInvoiceSendStatus,
  invoicingApproverList,
  qcc
} from '@/api/person/invoicing'
import { getToken } from '@/utils/auth'
import { validLowerCase } from '@/utils/validate'

export default {
  name: 'AddEditInvoicingDialog',
  components: {},
  dicts: ['invoice_type', 'invoice_transfer_method'],
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    operType: {
      type: String,
      default: 'add',
    },
    row: {
      type: Object,
      default: () => ({})
    },
    isEarly: {
      type: Boolean,
      default: false,
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.show
      },
      set(value) {
        this.$emit('update:show', value)
      }
    }
  },
  data() {
    return {
      userList: [],
      approverList: [],
      saleDeptList: [],
      agreementList: [],
      invoiceList: [],
      formData: {},
      formRules: {
        applyUser: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        applyDept: [],
        applyDate: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        entrustOrganizationId: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        agreements: [],
        applyDetails: [],
        invoiceType: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        sellingParty: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        invoiceNumber: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        invoiceDate: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        taxRate: [],
        invoiceHeaderId: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        invoiceHeaderName: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        taxId: [
          { required: false, message: '请输入', trigger: 'blur' }
        ],
        openBank: [],
        bankAccount: [],
        contactNumber: [],
        address: [],
        totalAmount: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        transferMethod: [],
        approveUser: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        remark: [],
        attachment: [],
      },
      contractRadioIndex: 0,
      // 文件上传参数
      uploadParams: {
        url: process.env.VUE_APP_BASE_API + '/system/oss/upload',
        headers: {
          Authorization: 'Bearer ' + getToken(),
          'Content-Disposition': 'inline'
        },
      },
      attachmentFileList: [],
      isAddInvoiceHeader: false,

      timer: null
    }
  },
  created() {
    this.initFormData()
  },
  methods: {
    // 弹框打开时
    handleDialogOpen() {
      if (this.operType == 'edit' || this.operType == 'update' || this.operType == 'detail') {
        invoicingDetail(this.row.invoiceApplyId).then(res => {
          for (let key in this.formData) {
            this.formData[key] = res.data[key]
          }
          this.formData.applyDetails = this.formData.applyDetails || []
          this.formData.invoiceDate = this.formData.invoiceDate || this.parseTime(new Date(), '{y}-{m}-{d}')
          this.attachmentFileList = JSON.parse(res.data.attachment || '[]')

          this.getInvoiceAgreement(false)
        }).catch(err => {})
        this.$nextTick(() => {
          this.$refs['clientOrganizationSelect'].setDefaultOption({
            entrustOrganizationId: this.row.entrustOrganizationId,
            organizationName: this.row.entrustOrganizationName
          })
        })
      }

      if (this.userList.length <= 0) {
        userListingIgnorePermission().then(res => {
          this.userList = res.data || []
        }).catch(err => {})
      }

      if (this.saleDeptList.length <= 0) {
        listDeptIgnorePermission({ pageNum: 1, pageSize: 10000, parentId: 0 }).then(res => {
          this.saleDeptList = res.data || []
        }).catch(err => {})
      }

      invoiceListAll().then(res => {
        this.invoiceList = res.data || []
      }).catch(err => {})

      this.getApproverList()
    },
    // 弹框关闭时
    handleDialogClosed() {
      this.initFormData()
      this.$refs.addEditInvoicingForm.resetFields()
      this.attachmentFileList = []
    },
    // 初始化表单数据
    initFormData() {
      this.formData = {
        applyUser: this.$store.state.user.userInfo?.userId || '',
        applyDept: '',
        applyDate: this.parseTime(new Date(), '{y}-{m}-{d}'),
        entrustOrganizationId: '',
        agreements: [],
        applyDetails: [],
        invoiceType: '',
        sellingParty: '',
        invoiceNumber: '',
        invoiceDate: this.parseTime(new Date(), '{y}-{m}-{d}'),
        taxRate: undefined,
        invoiceHeaderId: '',
        invoiceHeaderName: '',
        taxId: '',
        openBank: '',
        bankAccount: '',
        contactNumber: '',
        address: '',
        totalAmount: undefined,
        transferMethod: '',
        approveUser: '',
        remark: '',
        attachment: '',
      }
      this.isAddInvoiceHeader = false
    },
    // 获取表单数据
    getFormData() {
      const data = JSON.parse(JSON.stringify(this.formData))
      data.applyDetails.forEach(item => item.agreementId = data.agreements[this.contractRadioIndex].agreementId)
      data.attachment = JSON.stringify(this.attachmentFileList?.map(item => ({
        ossId: item.response?.data.ossId || item.ossId,
        url: item.response?.data.url || item.url,
        name: item.response?.data.name || item.name
      })) || [])
      if (this.operType == 'edit' || this.operType == 'update') {
        data.invoiceApplyId = this.row.invoiceApplyId
      }
      return data
    },
    // 获取审批人列表
    getApproverList() {
      const data = {
        deptId: this.formData.sellingParty || undefined,
        roleKeys: ['invoice_apply_approve']
      }
      invoicingApproverList(data).then(res => {
        this.approverList = res.data || []
        const findRes = this.approverList.find(item => item.defaultSelect)
        if (!findRes) return
        this.formData.approveUser = findRes.userId
      }).catch(err => {})
    },
    // 新增抬头编号
    handleAddInvoicHead() {
      this.isAddInvoiceHeader = !this.isAddInvoiceHeader
      this.formData.invoiceHeaderId = ''
      this.formData.invoiceHeaderName = ''
    },
    // 计算合计金额
    calculateActualAmount() {
      this.formData.totalAmount = this.formData.agreements.reduce((total, item) => {
        const num = Number(item.agreementInvoiceAmount)
        return total + (num || 0)
      }, 0)
    },
    // 获取关联合同
    getInvoiceAgreement(flag = false) {
      if (!this.formData.entrustOrganizationId) return
      queryInvoiceAgreement({ entrustOrganizationId: this.formData.entrustOrganizationId }).then(res => {
        this.agreementList = res.data || []
        if (flag) {
          this.formData.agreements = JSON.parse(JSON.stringify(this.agreementList))
        }
      }).catch(err => {})
    },
    // 新增关联合同
    handleAddContract() {
      if (!this.formData.entrustOrganizationId) {
        return this.$message.error('请先选择委托单位')
      }
      this.formData.agreements.push({
        agreementId: '',
        agreementInvoiceAmount: undefined
      })
      this.calculateActualAmount()
    },
    // 移除关联合同
    handleRemoveContract(index) {
      this.formData.agreements.splice(index, 1)
      this.calculateActualAmount()
    },
    // 新增开票明细
    handleAddDetail() {
      this.formData.applyDetails.push({
        agreementId: '',
        goodsName: '',
        specifications: '',
        unit: '',
        quantity: undefined,
        price: undefined,
        amount: undefined,
        detailTaxRate: undefined,
        taxAmount: undefined,
      })
    },
    // 移除开票明细
    handleRemoveDetail(index) {
      this.formData.applyDetails.splice(index, 1)
    },
    // 选择的销方公司改变
    handleSellingPartyChange(value) {
      this.formData.applyDept = value
      if (this.operType != 'update') {
        this.formData.approveUser = ''
        this.getApproverList()
      }
    },
    // 点击保存
    handleSave(isSubmit = true) {
      for(let i = 0; i < this.formData.agreements.length; i++) {
        if (!this.formData.agreements[i].agreementId) {
          return this.$message.error('请完善关联合同信息')
        } else if (!this.formData.agreements[i].agreementInvoiceAmount) {
          return this.$message.error('请完善关联合同信息')
        }
      }
      this.$refs.addEditInvoicingForm.validate(valid => {
        if (!valid) return
        let fn = null
        if (this.operType == 'add') fn = invoicingAdd
        else if (this.operType == 'edit') fn = invoicingEdit
        else if (this.operType == 'update') fn = invoicingOper
        const data = this.getFormData()
        data.submit = isSubmit
        fn(data).then(res => {
          this.$message.success('操作成功')
          this.dialogVisible = false
          this.$emit('refresh')
        }).catch(err => {})
      })
    },
    // 点击 发票已开并发送
    handleChangeSendStatus() {
      changeInvoiceSendStatus(this.row.invoiceApplyId).then(res => {
        this.$message.success('操作成功')
        this.dialogVisible = false
        this.$emit('refresh')
      }).catch(err => {})
    },

    // 文件上传前
		handleBeforeUpload(file) {
			// let isPDF = (file.type === 'application/pdf')
			// if (!isPDF) {
			// 	this.$message.warning('仅支持pdf格式，请重新上传!')
			// }
			// return isPDF
      return true
		},
    // 文件上传成功
    handleSuccessFile(res, file, fileList) {
			if (res.code == 500) {
				return this.$message.error(res.msg)
			}
			this.attachmentFileList = fileList
    },
    // 文件上传失败
    handleErrorFile(err, file, fileList) {
      this.$message.error('文件上传失败')
    },
    // 移除文件
    handleRemoveFile(file, fileList) {
      this.attachmentFileList = fileList
		},
    // 预览文件
    handlePreviewFile(file, fileList) {
			if (file.response && file.response.data) {
				window.open(file.response.data.url, 'PDF', '')
			} else if (file.url) {
				window.open(file.url, 'PDF', '')
			}
		},
    // 根据发票抬头获取企业其他信息
    handleInvoiceHeaderName() {
      if(this.formData.invoiceHeaderName) {
        qcc({keyWord:this.formData.invoiceHeaderName}).then(res => {
          this.$set(this.formData, 'taxId', res.data.creditCode);
          this.$set(this.formData, 'openBank', res.data.bank);
          this.$set(this.formData, 'bankAccount', res.data.bankAccount);
          this.$set(this.formData, 'contactNumber', res.data.tel);
          this.$set(this.formData, 'address', res.data.address);
        })
      }
    }
  },
  watch: {
    'formData.agreements': {
      handler(val) {
        if (this.formData.agreements.length > 0) {
          this.formData.agreements.forEach((item, index) => {
            if (!item.agreementInvoiceAmount) {
              item.agreementInvoiceAmount = (item.unInvoiceAmount || 0) - (item.progressInvoiceAmount || 0)
            }
          })

          if (this.timer) clearTimeout(this.timer)
          this.timer = setTimeout(() => {
            this.formData.sellingParty = this.formData.agreements[0].deptId
            this.handleSellingPartyChange(this.formData.sellingParty)
          }, 300)
        }
        this.calculateActualAmount()
      },
      deep: true
    },
  }
}
</script>

<style lang="scss" scoped>
.addedit-invoicing-dialog {

  ::v-deep .el-dialog__body {
    max-height: 85vh;
    overflow-y: auto;
  }

  .line-1 ::v-deep .el-form-item__label {
    line-height: 1;
  }

  .append {
    position: absolute;
    right: 10px;
  }
}
.qcc {
  width: 20px;
  height: 20px;
}
</style>
